package com.lehecai.core.search.api.impl.parser;

import com.lehecai.core.search.api.SearchApiConstant;
import com.lehecai.core.search.api.impl.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 按照command进行解析器的绑定
 * User: sunshow
 * Date: 13-4-6
 * Time: 下午1:22
 */
public class SearchApiResponseParserBinder {

    private static final Logger logger = LoggerFactory.getLogger(SearchApiResponseParserBinder.class);

    private static Map<String, Class<? extends AbstractSearchApiResponse>> classBinder = new HashMap<String, Class<? extends AbstractSearchApiResponse>>();

    private static Map<String, ISearchApiResponseBodyParser> parserBinder = new HashMap<String, ISearchApiResponseBodyParser>();

    private static void register(String command, Class<? extends AbstractSearchApiResponse> clazz, ISearchApiResponseBodyParser parser) {
        classBinder.put(command, clazz);
        parserBinder.put(command, parser);
    }

    static {
        register(SearchApiConstant.API_COMMAND_INSERT, InsertSearchApiResponse.class, null);
        register(SearchApiConstant.API_COMMAND_DELETE, DeleteSearchApiResponse.class, null);
        register(SearchApiConstant.API_COMMAND_UPDATE, UpdateSearchApiResponse.class, null);
        register(SearchApiConstant.API_COMMAND_SELECT, SelectSearchApiResponse.class, new SelectSearchApiResponseBodyParser());
        register(SearchApiConstant.API_COMMAND_AGGREGATE, AggregateSearchApiResponse.class, new AggregateSearchApiResponseBodyParser());
    }

    public static AbstractSearchApiResponse createInstance(String command) {
        Class<? extends AbstractSearchApiResponse> clazz = classBinder.get(command);
        if (clazz == null) {
            return null;
        }
        try {
            return clazz.newInstance();
        } catch (Exception e) {
            logger.error("实例化出错", e);
            logger.error("new instance: {}", clazz);
            return null;
        }
    }

    public static ISearchApiResponseBodyParser getParser(String command) {
        return parserBinder.get(command);
    }
}
